<?php


class UserController extends Zend_Controller_Action {

	protected $_user;
	protected $_mapper;

	public function init()
	{
		$this->_mapper = new Model_User_Mapper();
		$id = (int) $this->_getParam('id', null);
		$this->_user = $this->_mapper->load($id);
	}

	public function loginAction()
	{
		$form = new Form_User_Auth();
		$this->view->form = $form;
		if($this->getRequest()->isPost()){
			if($form->isValid($this->getRequest()->getPost())){
				$this->_mapper->authenticate($form->getValue('email'), $form->getValue('password'));
				$this->_redirect('/');
			}
		}
		Zend_Debug::dump(Zend_Auth::getInstance()->getIdentity());
	}


	public function registerAction()
	{
		$form = new Form_User_Register();
		$this->view->form = $form;
		if($this->getRequest()->isPost()){
			if($form->isValid($this->getRequest()->getPost())){
				$this->_mapper->fill($this->_user,$this->getRequest()->getPost());
				$this->_user->password = md5($this->_user->password);
				$this->_mapper->save($this->_user);
				$this->_mapper->authenticate($form->getValue('email'), $form->getValue('password'));
				$this->_redirect('/');
			} 
		}
	}
	
	public function editAction()
	{
	   $form = new Form_User_Edit($this->_user); 
    	if($this->getRequest()->isPost()){
                if($form->isValid($this->getRequest()->getPost())){
                    $this->_user->password = md5($this->_user->password);
                    $this->_mapper->save($this->_user);
                    $this->_redirect($_SERVER['HTTP_REFERER']);
                } 
            }
	}

	public function profileAction()
	{
	    $id = (int) $this->_getParam('id', null);
	    $this->_mapper->fill($this->_user,$this->getRequest()->getPost());
	    $this->view->user = $this->_user;
	    if(Zend_Auth::getInstance()->hasIdentity()){
	          
	        if(Zend_Auth::getInstance()->getIdentity()->id = $id){
	           
	            $form = new Form_User_Edit($this->_user); 
	            $this->view->form = $form;
	            if($this->getRequest()->isPost()){
	            
                    if($form->isValid($this->getRequest()->getPost())){
                        
                        
                        if($form->getValue('password') != ''){
                            $this->_user->password = md5($this->_user->password);
                            $ignored = array();
                        } else {
                            $ignored = array('password');
                        }
                        
                        $this->_mapper->save($this->_user, $ignored);
                       // $this->_redirect($_SERVER['HTTP_REFERER']);
                    }
                }
	        }
	    }
	}
}

